package com.yxhl.zoume.core.officialcar.presenter;

import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.yxhl.protobuf.CommonRespParams;
import com.yxhl.protobuf.MpvModel;
import com.yxhl.protobuf.MpvModelRequest;
import com.yxhl.protobuf.MpvModelResponse;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.protobuf.RentalTime;
import com.yxhl.zoume.R;
import com.yxhl.zoume.common.presenter.BasePresenter;
import com.yxhl.zoume.common.ui.view.BaseView;
import com.yxhl.zoume.core.car.view.common.GetRentCarTimeView;
import com.yxhl.zoume.core.car.view.common.VehicleShowView;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.domain.interactor.car.officialcar.QueryVehicleModelUseCase;
import com.yxhl.zoume.utils.DensityUtils;
import com.yxhl.zoume.utils.DeviceUtils;

import java.util.List;

import javax.inject.Inject;

import butterknife.ButterKnife;

/**
 * Created by sugarya on 16/8/22.
 * 车型查询Presenter 公务车/专车 复用
 */
public class InitializeOfficialCarPresenter extends BasePresenter {

    static final ButterKnife.Action<View> ARROW_INVISIBLE = new ButterKnife.Action<View>() {
        @Override
        public void apply(@NonNull View view, int index) {
            view.setVisibility(View.INVISIBLE);
        }
    };
    static final ButterKnife.Action<View> ARROW_VISIBLE = new ButterKnife.Action<View>() {
        @Override
        public void apply(@NonNull View view, int index) {
            view.setVisibility(View.VISIBLE);
        }
    };
    private static final String TAG = "InitializeOfficialCarPresenter";
    /**
     * 单个屏幕内需要显示的车辆数量
     */
    private static final int VEHICLE_COUNT = 3;
    //arguments
    @Inject
    QueryVehicleModelUseCase mQueryVehicleModelUseCase;

    private VehicleShowView mVehicleShowView;

    private GetRentCarTimeView mGetRentCarTimeView;

    private List<MpvModel> mVehicleModelsList;

    /**
     * 屏幕适配,车辆的显示宽度
     */
    private int mVehicleTotalDisplayWith;


    @Inject
    public InitializeOfficialCarPresenter(Context context) {
        super(context);
    }


    /**
     * 查询价格和距离
     *
     * @param bizType
     */
    public void queryOfficialCarDisplayData(OrderBizType bizType) {

        MpvModelRequest request = MpvModelRequest
                .newBuilder()
                .setCommonRequest(getCommonReqParams())
                .setBindType(bizType)
                .build();

        mQueryVehicleModelUseCase.execute(request,new ZMSubscriber<MpvModelResponse>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mVehicleShowView.renderVehicleModeDataOnError(e.toString());
                    }

                    @Override
                    public void onNext(MpvModelResponse mpvModelResponse) {
                        super.onNext(mpvModelResponse);
                        CommonRespParams commonResponse = mpvModelResponse.getCommonResponse();
                        if (commonResponse != null) {
                            String isSucc = commonResponse.getIsSucc();
                            if ("true".equalsIgnoreCase(isSucc)) {
                                mVehicleModelsList = mpvModelResponse.getVehicleModelsList();
                                if (mVehicleModelsList != null && mVehicleModelsList.size() >= 0) {
                                    mVehicleShowView.renderVehicleModelDataOnSuccess(mVehicleModelsList);
                                }

                                List<RentalTime> rentalTimesList = mpvModelResponse.getRentalTimesList();
                                if (rentalTimesList != null && rentalTimesList.size() >= 0) {
                                    if (mGetRentCarTimeView != null) {
                                        mGetRentCarTimeView.renderRentCarTimeOnSuccess(rentalTimesList);
                                    }
                                }

                            } else {
                                mVehicleShowView.renderVehicleModelDataOnFailure(commonResponse.getResultMsg());
                            }
                        }
                    }
                });

    }

    /**
     * 箭头初始化状态
     *
     * @param mArrowIvs
     */
    public void initializeArrowShow(List<ImageView> mArrowIvs) {
        int size = mVehicleModelsList.size();
        if (size >= 4) {
            ButterKnife.apply(mArrowIvs, ARROW_VISIBLE);
        } else {
            ButterKnife.apply(mArrowIvs, ARROW_INVISIBLE);
        }
    }


    /**
     * 初始化车型控件 网络url下载图片
     *
     * @param viewContainer
     */
    public void initializeVehicleShowByOnline(ViewGroup viewContainer) {
        int size = mVehicleModelsList.size();


        mVehicleTotalDisplayWith = DeviceUtils.getScreenWidth(mContext) - DensityUtils.dip2px(mContext, 40 * 2);
        int vehicleDisplayWith = mVehicleTotalDisplayWith / VEHICLE_COUNT;
        ColorStateList colorStateList = mContext.getResources().getColorStateList(R.color.color_single_way_check_car);

        if (viewContainer.getChildCount() < size) {
            for (int i = 0; i < size; i++) {
                MpvModel mpvModel = mVehicleModelsList.get(i);
                String modelName = mpvModel.getModelName();
                String modelType = mpvModel.getModelType();
                String imgDefaultUrl = mpvModel.getImgUrl();
                String imgSelectedUrl = mpvModel.getImgSelectedUrl();

                RadioButton radioButton = new RadioButton(mContext);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                        vehicleDisplayWith, LinearLayout.LayoutParams.WRAP_CONTENT);
                radioButton.setLayoutParams(layoutParams);

                radioButton.setButtonDrawable(mContext.getResources().getDrawable(R.color.transparent));
                radioButton.setGravity(Gravity.CENTER);
                radioButton.setTextColor(colorStateList);
                radioButton.setText(modelName);
                //数据传入Tag,作为创建小车订单的一个入参
                radioButton.setTag(modelType);

                //设置车型图片
                StateListDrawable stateListDrawable = new StateListDrawable();

                Picasso.with(mContext).load(imgDefaultUrl).into(new DefaultRadioTarget(stateListDrawable, radioButton));
                Picasso.with(mContext).load(imgSelectedUrl).into(new CheckedRadioTarget(stateListDrawable, radioButton));

                //添加视图
                if (viewContainer.getChildCount() < size) {
                    viewContainer.addView(radioButton);
                }
            }
        }

    }

    public int getVehicleTotalDisplayWith() {
        return mVehicleTotalDisplayWith;
    }

    @Override
    public void attachView(BaseView view) {
        if (view instanceof VehicleShowView) {
            mVehicleShowView = (VehicleShowView) view;
        }

        if (view instanceof GetRentCarTimeView) {
            mGetRentCarTimeView = (GetRentCarTimeView) view;
        }

    }


//    /**
//     * 初始化车型控件 使用本地图片
//     * @param viewContainer
//     */
//    public void initializeVehicleShowByLocal(ViewGroup viewContainer) {
//        int size = mVehicleModelsList.size();
//
//        mVehicleTotalDisplayWith = DeviceUtils.getScreenWidth(mContext) - DensityUtils.dip2px(mContext,40*2);
//        int vehicleDisplayWith = mVehicleTotalDisplayWith / VEHICLE_COUNT;
//        ColorStateList colorStateList = mContext.getResources().getColorStateList(R.color.color_single_way_check_car);
//
//        for(int i = 0; i < size; i++){
//            MpvModel mpvModel = mVehicleModelsList.get(i);
//            String modelName = mpvModel.getModelName();
//            String modelType = mpvModel.getModelType();
//
//            RadioButton radioButton = new RadioButton(mContext);
//            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
//                    vehicleDisplayWith, LinearLayout.LayoutParams.WRAP_CONTENT);
//            radioButton.setLayoutParams(layoutParams);
//
//            radioButton.setButtonDrawable(mContext.getResources().getDrawable(R.color.transparent));
//            radioButton.setGravity(Gravity.CENTER);
//            radioButton.setTextColor(colorStateList);
//            radioButton.setText(modelName);
//            radioButton.setTag(modelType);
//
//            //设置车型图片
//            StateListDrawable stateListDrawable = new StateListDrawable();
//
//            stateListDrawable.addState(new int[]{android.R.attr.state_checked}
//                    , mContext.getResources().getDrawable(getCheckedDrawableRes(modelType)));
//
//            stateListDrawable.addState(new int[]{-android.R.attr.state_checked}
//                    , mContext.getResources().getDrawable(getDefaultDrawableRes(modelType)));
//
//            radioButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, stateListDrawable);
//            radioButton.setCompoundDrawablePadding(DensityUtils.dip2px(mContext,20));
//
//            //添加视图
//            viewContainer.addView(radioButton);
//        }
//    }
//
//
//    private @DrawableRes
//    int getCheckedDrawableRes(String modelType){
//        int checkedRes;
//        switch (modelType){
//            case CarModelType.ORDINARY_CAR:
//                checkedRes = R.drawable.ic_putong_01;
//                break;
//            case CarModelType.COMFORTABLE_CAR:
//                checkedRes = R.drawable.ic_shushi_01;
//                break;
//            case CarModelType.LUXURY_CAR:
//                checkedRes = R.drawable.ic_haohua_01;
//                break;
//            case CarModelType.BUSINESS_CAR_SEVEN:
//                checkedRes = R.drawable.ic_7zuo_01;
//                break;
//            case CarModelType.BUSINESS_CAR_NINE:
//                checkedRes = R.drawable.ic_9zuo_01;
//                break;
//            case CarModelType.BUSINESS_CAR_ELEVEN:
//                checkedRes = R.drawable.ic_11zuo_01;
//                break;
//            default:
//                checkedRes = -1;
//        }
//
//        return checkedRes;
//    }
//
//    private @DrawableRes int getDefaultDrawableRes(String modelType){
//        int defaultRes;
//        switch (modelType){
//            case CarModelType.ORDINARY_CAR:
//                defaultRes = R.drawable.ic_putong_00;
//                break;
//            case CarModelType.COMFORTABLE_CAR:
//                defaultRes = R.drawable.ic_shushi_00;
//                break;
//            case CarModelType.LUXURY_CAR:
//                defaultRes = R.drawable.ic_haohua_00;
//                break;
//            case CarModelType.BUSINESS_CAR_SEVEN:
//                defaultRes = R.drawable.ic_7zuo_00;
//                break;
//            case CarModelType.BUSINESS_CAR_NINE:
//                defaultRes = R.drawable.ic_9zuo_00;
//                break;
//            case CarModelType.BUSINESS_CAR_ELEVEN:
//                defaultRes = R.drawable.ic_11zuo_00;
//                break;
//            default:
//                defaultRes = -1;
//        }
//
//        return defaultRes;
//    }

    class DefaultRadioTarget implements Target {

        StateListDrawable stateListDrawable;
        RadioButton radioButton;

        public DefaultRadioTarget(StateListDrawable stateListDrawable, RadioButton radioButton) {
            this.stateListDrawable = stateListDrawable;
            this.radioButton = radioButton;
        }


        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            stateListDrawable.addState(new int[]{-android.R.attr.state_checked}
                    , new BitmapDrawable(mContext.getResources(), bitmap));
            radioButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, stateListDrawable);
            radioButton.setCompoundDrawablePadding(DensityUtils.dip2px(mContext, 20));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    }

    class CheckedRadioTarget implements Target {

        StateListDrawable stateListDrawable;
        RadioButton radioButton;

        public CheckedRadioTarget(StateListDrawable stateListDrawable, RadioButton radioButton) {
            this.stateListDrawable = stateListDrawable;
            this.radioButton = radioButton;
        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            stateListDrawable.addState(new int[]{android.R.attr.state_checked}
                    , new BitmapDrawable(mContext.getResources(), bitmap));

            radioButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, stateListDrawable);
            radioButton.setCompoundDrawablePadding(DensityUtils.dip2px(mContext, 20));
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
        }
    }
}
